#include "registrationdialog.h"

#include <QStackedWidget>
#include <QFormLayout>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLineEdit>
#include <QPushButton>
#include <QLabel>
#include <QCryptographicHash>
#include <QMessageBox>

namespace Ui {

RegistrationDialog::RegistrationDialog(QWidget *parent) : QDialog(parent) {
	setModal(true);

	userName = new QLineEdit(this);

	password1 = new QLineEdit(this);
	password1->setEchoMode(QLineEdit::Password);

	password2 = new QLineEdit(this);
	password2->setEchoMode(QLineEdit::Password);

	formLayout = new QFormLayout();
	formLayout->addRow("Login", userName);
	formLayout->addRow("Password", password1);
	formLayout->addRow("", password2);

	okButton = new QPushButton(tr("&Ok"), this);
	connect(okButton, SIGNAL(clicked()), this, SLOT(ok()));
	cancelButton = new QPushButton(tr("&Cancel"), this);
	connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject()));

	buttonsLayout = new QHBoxLayout();
	buttonsLayout->addWidget(okButton);
	buttonsLayout->addWidget(cancelButton);

	mainLayout = new QVBoxLayout(this);
	mainLayout->addLayout(formLayout);
	mainLayout->addLayout(buttonsLayout);

	setWindowTitle(tr("Registration Dialog"));
	show();
}

RegistrationDialog::~RegistrationDialog() {
	delete userName;
	delete password1;
	delete password2;
	delete okButton;
	delete cancelButton;
	delete formLayout;
	delete buttonsLayout;
	delete mainLayout;
}

void RegistrationDialog::ok() {
	QString user = userName->text();
	QString password = ((password1->text() == password2->text())?password1->text():"");
	if(!(user.isEmpty() || password.isEmpty())) {
		emit registration(user,QString(QCryptographicHash::hash(password.toUtf8(), QCryptographicHash::Md5)));
//		emit registration(user,password);
		QMessageBox::information(this, "Registration", "Your registration will be sent to server.");
		accept();
	}
	else {
		QMessageBox::critical(this, "Invalid Data", "You must fill all fields and type the same password in the last two. Do it again.");
		password1->clear();
		password2->clear();
	}
}

}

